#!/usr/bin/env python3
import os
from database.mysql_manager import db_manager

"""
强制插入MySQL订单初始数据的脚本
直接插入数据，不进行数据存在性检查
"""

def force_insert_order_data():
    print("===== 强制插入MySQL订单初始数据工具 =====")
    
    try:
        # 连接到数据库
        print("\n正在连接到MySQL数据库...")
        if not db_manager.connect():
            print("❌ 无法连接到数据库，请检查MySQL服务和配置")
            return False
        
        print("✅ 成功连接到数据库")
        
        # 开始事务
        db_manager.connection.begin()
        
        try:
            # 清除现有订单数据（避免数据冲突）
            print("\n正在清除现有订单数据...")
            # 先删除订单项（避免外键约束问题）
            item_count = db_manager.execute_update("DELETE FROM order_items;")
            # 再删除订单
            order_count = db_manager.execute_update("DELETE FROM orders;")
            print(f"✅ 已清除 {order_count} 个订单和 {item_count} 个订单项")
            
            # 插入订单数据
            print("\n正在插入初始订单数据...")
            orders = [
                ('ORD-20240001', '张三', 'zhangsan@example.com', 1599.00, 'completed'),
                ('ORD-20240002', '李四', 'lisi@example.com', 899.50, 'pending'),
                ('ORD-20240003', '王五', 'wangwu@example.com', 2399.00, 'completed'),
            ]
            order_query = """
                INSERT INTO orders (order_no, customer_name, customer_email, total_amount, status)
                VALUES (%s, %s, %s, %s, %s)
            """
            db_manager.execute_many(order_query, orders)
            
            # 获取刚插入的订单ID
            orders_data = db_manager.execute_query("SELECT id, order_no FROM orders;")
            order_map = {order['order_no']: order['id'] for order in orders_data}
            
            # 插入订单项数据
            print("\n正在插入订单项数据...")
            order_items = [
                # 订单ORD-20240001的商品
                (order_map['ORD-20240001'], '智能手表', 1, 1599.00),
                # 订单ORD-20240002的商品
                (order_map['ORD-20240002'], '蓝牙耳机', 2, 449.75),
                # 订单ORD-20240003的商品
                (order_map['ORD-20240003'], '笔记本电脑', 1, 2399.00),
                # 额外的测试数据
                (order_map['ORD-20240001'], '充电线', 1, 49.00),
                (order_map['ORD-20240003'], '鼠标', 1, 99.00),
            ]
            order_item_query = """
                INSERT INTO order_items (order_id, product_name, quantity, unit_price)
                VALUES (%s, %s, %s, %s)
            """
            db_manager.execute_many(order_item_query, order_items)
            
            # 提交事务
            db_manager.connection.commit()
            
            # 验证数据是否插入成功
            print("\n正在验证数据插入结果...")
            final_order_count = db_manager.execute_query("SELECT COUNT(*) as count FROM orders;")[0]['count']
            final_item_count = db_manager.execute_query("SELECT COUNT(*) as count FROM order_items;")[0]['count']
            
            print(f"✅ 成功插入了 {final_order_count} 个订单和 {final_item_count} 个订单项")
            
            # 查询一些订单数据进行展示
            sample_orders = db_manager.execute_query("""
                SELECT id, order_no, customer_name, total_amount, status
                FROM orders
                LIMIT 3
            """)
            
            if sample_orders:
                print("\n已插入的订单数据示例:")
                for order in sample_orders:
                    print(f"- 订单号: {order['order_no']}, 客户: {order['customer_name']}, \
                      总金额: ¥{order['total_amount']:.2f}, 状态: {order['status']}")
            
            # 关闭连接
            db_manager.disconnect()
            print("\n✅ MySQL订单数据强制插入完成!")
            return True
            
        except Exception as e:
            # 回滚事务
            db_manager.connection.rollback()
            print(f"❌ 插入数据时出错并已回滚: {e}")
            db_manager.disconnect()
            return False
            
    except Exception as e:
        print(f"❌ 强制插入过程中发生错误: {e}")
        db_manager.disconnect()
        return False

def main():
    print("MySQL订单数据强制插入工具")
    print("======================")
    print("警告：此工具会删除现有订单数据并重新插入初始数据")
    
    # 运行强制插入过程
    success = force_insert_order_data()
    
    if success:
        print("\n恭喜！订单数据已成功插入。")
        print("你现在可以重启服务并通过API访问这些订单数据。")
    else:
        print("\n强制插入失败，请检查错误信息并修复问题后重试。")

if __name__ == "__main__":
    main()